#-*- utf-8 -*-
# 导入模块
import hashlib
from flask import Flask, request, make_response
from wechatpy import parse_message, create_reply, WeChatClient
import time
import yaml
from gptManage import gptMessageManage

##############################读取配置##########################
with open('config/config.yml', 'r') as f:
    configs = yaml.load(f, Loader=yaml.FullLoader)
##############################设置微信相关参数##########################
appid = configs['wechat']['appid']
secret = configs['wechat']['secret']
if configs['wechat']['ip_detection'] or configs['azure']['trans_to_voice']:
    client = WeChatClient(appid, secret)
else: 
    client = ''
wechattoken = configs['wechat']['token']

##############################openai基础设置##########################
msgsmanag = gptMessageManage(client,configs)


app = Flask(__name__)
app.debug = True

#验证是否部署成功
@app.route("/")
def hello():
    return "Hello"

@app.route('/wechat/', methods=['GET', 'POST']) 
def wechat():
    global reply
    global msgsmanag
    global wechattoken
    if request.method == 'GET':
        token = wechattoken# 设置 wechat token
        data = request.args
        signature = data.get('signature', '')
        timestamp = data.get('timestamp', '')
        nonce = data.get('nonce', '')
        echostr = data.get('echostr', '')
        s = sorted([timestamp, nonce, token])
        s = ''.join(s)
        if hashlib.sha1(s.encode('utf-8')).hexdigest() == signature:
            response = make_response(echostr)
            return response
    else:
        msg = parse_message(request.get_data())
        if msg.type == 'text':
            cctime = int(time.time())
            # 内置英语对话模板
            if msg.content[:4]=='英语对话':
                tt = "be my English teacher"
                rtext = msgsmanag.get_response(msg,cctime,tt)
            else:
                rtext = msgsmanag.get_response(msg,cctime,msg.content)
            rt = str(rtext).strip()
            reply = create_reply(rt, message=msg)#创建消息
            return reply.render()
        if msg.type == 'image':
            rtext = '您发送了一张图片！'
            reply = create_reply(rtext, message=msg)#创建消息
            return reply.render()#回复消息
        return ''


if __name__ == '__main__':
    app.run( host = '0.0.0.0',port=80)
